import { ref, onMounted } from 'vue'

export const useFavorite = () => {
  const favoriteList = ref<any[]>([])

  // 初始化收藏列表
  const initFavoriteList = () => {
    try {
      const stored = window.localStorage.getItem('favoriteList')
      favoriteList.value = stored ? JSON.parse(stored) : []
    } catch (error) {
      console.error('初始化收藏列表失败:', error)
      favoriteList.value = []
    }
  }

  // 判断是否收藏
  const isMarkapp = (markapp: any) => {
    return favoriteList.value.some((item: any) => item.id === markapp.id)
  }

  // 添加收藏
  const handleMarkapp = (markapp: any) => {
    logEvent('Click_Favor_Tag', {
      App: markapp.name,
      type: 'Favor'
    })
    favoriteList.value.unshift(markapp)
    window.localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value))
  }

  // 移除收藏
  const removeMarkapp = (markapp: any) => {
    logEvent('Click_Favor_Tag', {
      App: markapp.name,
      type: 'UnFavor'
    })
    favoriteList.value = favoriteList.value.filter((item: any) => item.id !== markapp.id)
    window.localStorage.setItem('favoriteList', JSON.stringify(favoriteList.value))
  }

  // 获取收藏列表
  const getFavoriteList = () => {
    return favoriteList.value
  }

  // 清空收藏列表
  const clearFavoriteList = () => {
    favoriteList.value = []
    window.localStorage.removeItem('favoriteList')
  }

  // 检查收藏数量
  const getFavoriteCount = () => {
    return favoriteList.value.length
  }

  // 在组件挂载时自动初始化
  onMounted(() => {
    initFavoriteList()
  })

  return {
    favoriteList,
    initFavoriteList,
    isMarkapp,
    handleMarkapp,
    removeMarkapp,
    getFavoriteList,
    clearFavoriteList,
    getFavoriteCount
  }
}
